"""
接入微博
"""
# encoding:utf-8
import base64
import hmac
import json
import pickle
import time
import traceback
import logging
import urllib
from datetime import datetime
from hashlib import sha256
from io import BytesIO
import random
from urllib.parse import urlencode

import requests
from flask import Blueprint, request, g, make_response, redirect
from flask_restful import Resource, Api, reqparse, marshal, fields, current_app

from common.utils.custom_output_json import custom_output_json
from common.utils.jwt_util import _generate_token, refresh_token
from common.models import rds, db, cache
from common.models.user import UserBase, OauthUser
from common.model_fields.user_fields import user_fields
from common.utils.utils import generate_code

oauth2_bp = Blueprint('oauth2_bp', __name__, url_prefix='/oauth2')
api = Api(oauth2_bp)


@api.representation('application/json')
def output_json(data, code=200, headers=None):
    return custom_output_json(data, code, headers)


class DingDingCallBack(Resource):
    """
    钉钉三方登录回调
    """

    # TODO 完善代码  怎么验证、验证成功之后要做什么
    def get(self):
        # TODO 参数
        t = time.time()
        # 时间戳
        timestamp = str((int(round(t * 1000))))
        appSecret = 'Fcah25vIw-koApCVN0mGonFwT2nSze14cEe6Fre8i269LqMNvrAdku4HRI2Mu9VK'
        # 构造签名
        signature = base64.b64encode(
            hmac.new(appSecret.encode('utf-8'), timestamp.encode('utf-8'), digestmod=sha256).digest())
        # 请求接口，换取钉钉用户名
        payload = {'tmp_auth_code': code}
        headers = {'Content-Type': 'application/json'}
        res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature=' + urllib.parse.quote(
            signature.decode("utf-8")) + "&timestamp=" + timestamp + "&accessKey=dingoajf8cqgyemqarekhr",
                            data=json.dumps(payload), headers=headers)

        # res_dict = json.loads(res.text)
        res_json = res.json()
        if res_json['errcode'] != 0:
            return {'message': res_json['errmsg'], 'code': 500, 'data': {'uid': '110'}}
        return {}


class BindDingDing(Resource):
    """
    绑定钉钉账号
    """
    def post(self):
        pass


api.add_resource(DingDingCallBack, '/user_dingding', endpoint='dingding')
api.add_resource(BindDingDing, '/user_dingding/bind', endpoint='dingding/bind')
